package org.test.httpclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class SimpleClient {
	public static void main(String[] args) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();

		// 可以这么组装请求参数
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("q", "httpclient"));
		qparams.add(new BasicNameValuePair("btnG", "Google Search"));
		qparams.add(new BasicNameValuePair("aq", "f"));
		qparams.add(new BasicNameValuePair("oq", null));
		URLEncodedUtils.format(qparams, "UTF-8");

		// 协议，host，端口（这里为默认）,请求资源，请求参数，optional fragment
		URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
				"q=httpclient&btnG=Google+Search&aq=f&oq=", null);

		// 提交方式有GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS.
		// HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete,
		// HttpTrace,HttpOptions.
		// 只有POST and PUT 可以包含content
		HttpGet httpget = new HttpGet(uri);

		System.out.println("-----------------响应头---------------------------");
		HttpResponse response = httpclient.execute(httpget);
		Header[] headers = response.getAllHeaders();
		for (Header h : headers) {
			System.out.println(h);
		}

		System.out.println("-----------------响应头中包含的cookie-----------------------------");

		HeaderIterator it = response.headerIterator("Set-Cookie");

		while (it.hasNext()) {
			System.out.println(it.next());
		}

		System.out.println("-----------------请求和响应中可以生成的content---------------------------------");

		StringEntity myEntity = new StringEntity("important message", "UTF-8");
		myEntity.setChunked(true);//选择最合适的编码

		System.out.println(myEntity.getContentType());
		System.out.println(myEntity.getContentLength());
		System.out.println(EntityUtils.getContentCharSet(myEntity));
		System.out.println(EntityUtils.toString(myEntity));
		System.out.println(EntityUtils.toByteArray(myEntity).length);

		System.out.println("-----------------请求中动态生成的content---------------------------------");

		ContentProducer cp = new ContentProducer() {
			public void writeTo(OutputStream outstream) throws IOException {
				Writer writer = new OutputStreamWriter(outstream, "UTF-8");
				writer.write("<response>");
				writer.write("  <content>");
				writer.write("    important stuff");
				writer.write("  </content>");
				writer.write("</response>");
				writer.flush();
			}
		};

		HttpPost httppost = new HttpPost("http://localhost/handler.do");
		HttpEntity entityTemplate = new EntityTemplate(cp);
		httppost.setEntity(entityTemplate);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("param1", "value1"));
		formparams.add(new BasicNameValuePair("param2", "value2"));
		//生成表单的entity
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		httppost.setEntity(formEntity);

		System.out.println("-----------------响应中的content---------------------------------");
		HttpEntity entity = response.getEntity();
		if (entity != null) {

			// entity = new BufferedHttpEntity(entity);//将content缓存在内存中，可以多次使用

			InputStream instream = entity.getContent();
			long len = entity.getContentLength();
			if (len != -1 && len < 2048) {
				System.out.println(EntityUtils.toString(entity));
			}
			int l;
			byte[] tmp = new byte[2048];//一个content最多2048byte
			while ((l = instream.read(tmp)) != -1) {
			}
		}
	}
}
